package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.common.R;
import com.example.pojo.entity.WmNews;
import com.example.service.NewsService;
import com.example.service.impl.NewsServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static com.example.utils.JsonChangeObject.JsonObject;

@WebServlet("/publish")
public class PublishNews extends HttpServlet {

    NewsService newsService = new NewsServiceImpl();

    /**
     * 发布文章
     */
    public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        String token = req.getHeader("token");
        String jsonStr = JsonObject(req);
        WmNews wmNews = JSON.parseObject(jsonStr, WmNews.class);

        R addNews = null;
        try {
            addNews = newsService.addNews(wmNews, token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //返回结果
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(JSON.toJSONString(addNews));
    }
}
